/**
 * MongoDB
 */

const mongoose = require('mongoose');
const globalConfig = require('../../config/global_config');
const mongodbConfig = globalConfig.mongodb;

function connect(callback) {
    const uri = 'mongodb://' + mongodbConfig.host + ':' + mongodbConfig.port + '/' + mongodbConfig.database;
    const connectionString = mongodbConfig.host + ':' + mongodbConfig.port + '/' + mongodbConfig.database;
    mongoose.Promise = global.Promise;
// mongoose.set('debug', true);
    const options = {
        user: mongodbConfig.user,
        pass: mongodbConfig.pass,
        poolSize: 10,
        useMongoClient: true,
        socketTimeoutMS: 0,
        keepAlive: true,
        reconnectTries: 30
    };
    mongoose.connect(uri, options, function (err, res) {
        if (err) {
            console.log('[mongoose] Error connecting to: ' + connectionString + '. ' + err)
            return process.exit(1)
        } else {
            return console.log('[mongoose] Successfully connected to: ' + connectionString)
        }
    });

    mongoose.connection.on('error', console.error.bind(console, 'mongoose connection error:'))
    mongoose.connection.once('open', callback);
}

exports.connect = connect;
